'use client';

import {
  BriefcaseIcon,
  Cog6ToothIcon,
  KeyIcon,
  PhotoIcon,
  StarIcon,
  MagnifyingGlassIcon,
  QuestionMarkCircleIcon,
} from '@heroicons/react/24/outline';
import clsx from 'clsx';
import React, { useCallback, useMemo, useState } from 'react';
import { Profile } from 'src/app/components/Profile';
import { Logo } from 'src/components/Icons';
import { Menu } from '../components/Menu';
import { usePathname } from 'next/navigation';
import { SiderToggle } from './SiderToggle';
import { ThemeController } from 'src/app/components/ThemeController';

export interface SiderProps {
  className?: string;
  expanded?: boolean;
  onExpand?: (expanded: boolean) => void;
}

function SiderNoMemoized(props: SiderProps) {
  const { className, expanded, onExpand } = props;

  // Global state
  const pathname = usePathname();

  // State
  const [innerExpanded, setInnerExpanded] = useState(false);

  // Memoized
  const finalExpanded = useMemo(() => expanded ?? innerExpanded, [expanded, innerExpanded]);

  const style = useMemo<React.CSSProperties>(
    () => ({
      width: finalExpanded ? 240 : 80,
      transition: 'width 0.2s ease-in-out',
    }),
    [finalExpanded]
  );

  const menus = useMemo(
    () => [
      {
        key: 'search',
        icon: <MagnifyingGlassIcon className="size-5" />,
        label: '搜索',
        href: '/workbench/home',
      },
      {
        key: 'my',
        icon: <BriefcaseIcon className="size-5" />,
        label: '我的资源',
        children: [
          {
            key: 'gallery',
            icon: <PhotoIcon className="size-5" />,
            label: '我的图库',
            href: '/workbench/gallery',
          },
          {
            key: 'favorites',
            icon: <StarIcon className="size-5" />,
            label: '收藏夹',
            href: '/workbench/favorites',
          },
        ],
      },
      {
        key: 'apiKeys',
        icon: <KeyIcon className="size-5" />,
        label: 'API Keys',
        href: '/workbench/api-keys',
      },
      {
        key: 'settings',
        icon: <Cog6ToothIcon className="size-5" />,
        label: '设置',
        href: '/workbench/settings',
      },
    ],
    []
  );

  const handleExpand = useCallback(
    (newExpanded: boolean) => {
      setInnerExpanded(newExpanded);
      onExpand?.(newExpanded);
    },
    [onExpand]
  );

  return (
    <nav className={clsx('relative z-[99]', className)} style={style}>
      {finalExpanded && (
        <SiderToggle
          className="absolute top-8 -right-3 z-10"
          size="xs"
          expanded={finalExpanded}
          onExpand={handleExpand}
        />
      )}
      <div aria-label="inner" className="absolute inset-0 size-full flex flex-col overflow-hidden">
        <div
          aria-label="logo"
          className={clsx(
            'flex-none w-full h-20 flex items-center px-5',
            finalExpanded && 'justify-between'
          )}
        >
          <div
            className={clsx(
              'relative inline-flex items-center gap-2 transition-all duration-300 ease-in-out',
              !finalExpanded && 'delay-300 scale-110'
            )}
          >
            <span className="absolute top-0 left-0 size-5 rounded-full bg-purple-400 dark:bg-purple-900 z-0" />
            <Logo className="size-9 flex-none relative z-10" />
            <span
              className={clsx(
                'text-2xl font-zcool whitespace-nowrap overflow-hidden',
                !finalExpanded && 'hidden'
              )}
            >
              星恒云图
            </span>
          </div>
        </div>
        <div aria-label="user" className="flex-none h-16 px-5 pt-2 flex items-start justify-center">
          <Profile block={finalExpanded} className={clsx(!finalExpanded && 'text-xs')} />
        </div>
        <div aria-label="menus" className="flex-auto overflow-auto scrollbar-none">
          <Menu selectedKey={pathname} menus={menus} allExpanded inlineCollapsed={!finalExpanded} />
        </div>
        {finalExpanded ? (
          <div
            aria-label="advertisement"
            className="flex-none flex flex-col items-center justify-center gap-4 py-4"
          >
            <div className="flex flex-col rounded-xl shadow-lg w-48 border border-purple-500 bg-gradient-to-br from-purple-500 to-purple-950 dark:brightness-75">
              <div className="px-5 py-4">
                <div className="grid items-center justify-center w-full grid-cols-1 text-left">
                  <div>
                    <h2 className="text-base font-medium tracking-tighter text-white">接入服务</h2>
                    <p className="mt-2 text-sm text-purple-300">使用 API SDK 处理图片</p>
                  </div>
                </div>
              </div>
              <div className="flex px-6 pb-4">
                <a
                  className={clsx(
                    'flex items-center justify-center w-full px-5 py-2 text-sm text-center duration-200 bg-black border-2 rounded-full focus:outline-none',
                    'text-white border-black',
                    'hover:bg-transparent hover:border-black hover:text-black'
                  )}
                  href="#"
                >
                  查看文档
                </a>
              </div>
            </div>
            <span className="text-xs text-gray-400 font-mono">images.nebulaedata.cn</span>
          </div>
        ) : (
          <div
            aria-label="toolbar"
            className="flex-none flex flex-col items-center justify-center gap-2 py-4"
          >
            <button
              type="button"
              className="btn btn-ghost btn-circle border-none ring-0 hover:bg-gray-200 dark:hover:bg-neutral-700"
              title="帮助"
            >
              <QuestionMarkCircleIcon className="size-5" />
            </button>
            <ThemeController />
            <SiderToggle className="mt-2" expanded={finalExpanded} onExpand={handleExpand} />
          </div>
        )}
      </div>
    </nav>
  );
}

export const Sider = React.memo(SiderNoMemoized);
